<script setup lang="ts">
import { ref, computed } from 'vue'

const price = ref(25)
const quantity = ref(2)
const discount = ref(0.8)

// 计算购物车总价
const total = computed<number>(() => {
  return price.value * quantity.value * discount.value
})

// 再来一杯
const add = () => quantity.value++

// 减少一杯
const remove = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// 重置数量
const reset = () => {
  quantity.value = 1
}
</script>

<template>
  <div class="card">
    <h2>🌟 关卡 3｜computed：声明式"衍生数据"</h2>
    
    <div class="coffee-shop">
      <h3>🧋 奶茶店</h3>
      
      <div class="order-info">
        <p>单价：{{ price }} 元</p>
        <p>数量：{{ quantity }}</p>
        <p>折扣：{{ discount * 10 }} 折</p>
      </div>
      
      <div class="quantity-controls">
        <button @click="remove" :disabled="quantity <= 1">-</button>
        <span>{{ quantity }}</span>
        <button @click="add">+</button>
        <button @click="reset" class="reset-btn">重置</button>
      </div>
      
      <h4 class="total-price">应付：{{ total.toFixed(2) }} 元</h4>
    </div>
    
    <div class="explanation">
      <h4>📝 学习要点</h4>
      <ul>
        <li>根据已有响应式数据自动计算出值，带缓存</li>
        <li>不要修改 computed 本身，它是"只读精灵"</li>
      </ul>
      <p class="funny">💡 趣味比喻：computed 像"自动奶茶机"，你放原料（ref/reactive），它自动出奶茶（计算结果），原料不变奶茶不重新做。</p>
    </div>
  </div>
</template>

<style scoped>
.coffee-shop {
  margin: 2em 0;
}

.coffee-icon {
  width: 80px;
  height: 80px;
}

.order-info {
  display: flex;
  justify-content: space-around;
  margin: 1em 0;
  font-size: 1.1em;
}

.quantity-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin: 1em 0;
}

.quantity-controls button {
  width: 40px;
  height: 40px;
  padding: 0;
  font-size: 1.2em;
}

.quantity-controls span {
  min-width: 40px;
  font-size: 1.2em;
  font-weight: bold;
}

.reset-btn {
  width: auto;
  padding: 0.3em 0.8em;
  font-size: 0.9em;
  background-color: #999;
}

.total-price {
  font-size: 1.5em;
  color: #ff5722;
  margin-top: 1em;
}

.explanation {
  text-align: left;
  margin-top: 2em;
}

.funny {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 1em;
  border-radius: 8px;
  font-style: italic;
}
</style>